package com.ocp.socket.server.mina;

import com.alibaba.fastjson.JSON;
import com.example.app.base.ResultStatus;
import com.ocp.socket.common.Constants;
import com.ocp.socket.common.bean.UserInfo;
import com.ocp.socket.common.enums.MsgTypeEnum;
import com.ocp.socket.common.utils.CommonUtils;
import com.ocp.socket.common.utils.SessionUtil;
import com.ocp.socket.server.service.*;
import com.ocp.socket.server.vo.MessageVo;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

/**
 * @Auther: zhangzh
 * @Date: 2019/1/23 10:14
 * @Description:
 * @Version: 1.0.0
 */
public class MinaLongConnServerHandler extends IoHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(MinaLongConnServerHandler.class);

    @Autowired
    private TempService tempService;
    @Autowired
    private AirpService airpService;
    @Autowired
    private MilkService milkService;
    @Autowired
    private AppService appService;



    @Override
    public void sessionCreated(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        super.sessionCreated(session);
    }
    /**
     * 一个客户端连接时回调的方法
     * @param session
     * @throws Exception
     */
    @Override
    public void sessionOpened(IoSession session) {
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();
        String hostAddress = remoteAddress.getAddress().getHostAddress();
        logger.info("创建新的连接ID：[{}];IP地址：[{}]", session.getId(), hostAddress);
    }


    /**
     * 接收到消息时回调的方法
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void messageReceived(IoSession session, Object message) {
        MessageVo messageVo = (MessageVo) message;
        boolean isAppMsg = false;
        ResultStatus resultStatus = null;
        if("0".equals(messageVo.getReturnCode())){//正常解析后存入数据
            if(MsgTypeEnum.TEMP.getTypeCode().equals(messageVo.getModel())){
                tempService.saveTemperatureData(messageVo,session);
            }else if(MsgTypeEnum.AIRP.getTypeCode().equals(messageVo.getModel())){
                airpService.savePressureData(messageVo,session);
            }else if(MsgTypeEnum.NORM.getTypeCode().equals(messageVo.getModel())){
                logger.info("{}类型报文",MsgTypeEnum.NORM.getTypeCode());
            }else if("MILK".equals(messageVo.getModel())){
                try{
                    milkService.saveMilkData(messageVo,session);
                }catch (Exception e){
                    logger.error("保存挤奶信息失败", e);
                }
            }else if(MsgTypeEnum.C.getTypeCode().equals(messageVo.getModel())){
                isAppMsg = true;
                resultStatus = appService.saveApp0002Data(messageVo,session);
            }

//            else if("AIRP".equals(messageVo.getModel())){
//                pressureService.savePressureData(messageVo);
//            }else if("MILK".equals(messageVo.getModel())){
//                milkService.saveMilkData(messageVo);
//            }
        }
        //返回信息拼接
        StringBuffer returnVal = new StringBuffer();
        if(isAppMsg){
            if(messageVo != null){
                //获取设备信息
                UserInfo userInfo = (UserInfo) session.getAttribute(Constants.ATTRIBUTE_KEY_AUTH);
                returnVal.append(CommonUtils.toMsg(messageVo.getModel(),messageVo.getSn(),messageVo.getDataTime(),JSON.toJSON(resultStatus).toString()));
                SessionUtil.sendAppUserMsgByOrgId(session,userInfo.getOrgId(),returnVal.toString());
            }
        }else if(MsgTypeEnum.NORM.getTypeCode().equals(messageVo.getModel())){
            if(messageVo != null){
                //获取设备信息
                returnVal.append(CommonUtils.toMsg(messageVo.getModel(),messageVo.getSn(),messageVo.getDataTime(),null));
            }
        }else{
            if(messageVo != null && messageVo.getDataHeader()!=null){
                returnVal.append(messageVo.getDataHeader());
            }
            if(messageVo != null && messageVo.getReturnCode()!=null){
                returnVal.append(messageVo.getReturnCode());
            }
            if(messageVo != null && messageVo.getReturnMsg()!=null){
                returnVal.append(messageVo.getReturnMsg());
            }
            //发送消息给客户端
            session.write(returnVal.toString());
        }

    }


    /**
     * 发送消息时回调的方法
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void messageSent(IoSession session, Object message)
            throws Exception {
        // TODO Auto-generated method stub
        logger.info("messageSent:{}", message);
        super.messageSent(session, message);
    }

    /**
     * 一个客户端断开时回调的方法
     * @param session
     * @throws Exception
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        logger.info("sessionClosed:{}",session.getId());
        //删除session的队列信息
        SessionUtil.removeSession(session);
        SocketManager.getInstance().removeSessionToOnlineMap(session.getId());
        super.sessionClosed(session);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        logger.info("Disconnectingthe idle.");
        // disconnect an idle client
//        SocketManager.getInstance().removeSessionToOnlineMap(session.getId());
//        session.closeNow();
        String return_msg = "心跳";
        //发送消息给客户端
        try{
            session.write(return_msg);
        }catch (Exception e){
            logger.info("发送心跳失败，关闭:{}", session.getId());
            session.closeNow();
            SocketManager.getInstance().removeSessionToOnlineMap(session.getId());
        }
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {

        // close the connection onexceptional situation

        logger.error("异常：{}",cause.getMessage(), cause);

        //        session.close(true);
        //发送消息给客户端
//        try{
//            session.write(cause.getMessage());
//        }catch (Exception e){
//            logger.info("异常后发送客户端:"+session.getId());
//            session.closeNow();
//            SocketManager.getInstance().removeSessionToOnlineMap(session.getId());
//        }
    }

}

